<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mobile_oauth_module extends CI_Module
{
    public function __construct(){
        parent::__construct();
        $this->load->model('weixin.weixin_model');
        $this->setting = $this->weixin_model->db_get_setting();
        define('TOKEN',     @$this->setting['token']);
        define('APPID',     @$this->setting['appid']);
        define('APPSECRET', @$this->setting['appsecret']);

    }

    public function oauth()
    {
        $redirect_uri = site_url('mobile/oauth/redirect_oauth');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.APPID.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
        redirect($url);
    }

    public function redirect_oauth()
    {
        $code= $this->input->get_post('code');
        $state= $this->input->get_post('state');
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.APPID.'&secret='.APPSECRET.'&code='.$code.'&grant_type=authorization_code';
        $access = file_get_contents($token_url);
        $access = (array)json_decode($access);

        if(!empty($access['openid']))
        {
            $this->weixin_model->initialize_login($access['openid']);
            $redirect = $this->session->userdata('redirect_uri');
            $uri = !empty($redirect) ? $redirect : site_url('mobile/member/center');
            redirect($uri);
        }

    }


}